<template>
  <div class="panel latest-activity-panel">
    <div class="panel-header">
      <i class="fas fa-stream" />
      <span>最新动态</span>
      <div class="auto-refresh">
        <el-icon v-if="isRefreshing" class="refresh-icon rotating">
          <Refresh />
        </el-icon>
        <span v-if="!isRefreshing" class="refresh-text">{{ lastUpdateTime }}</span>
      </div>
    </div>

    <div class="activity-list">
      <!-- 最新评论 -->
      <div v-if="latestComments.length > 0" class="activity-section">
        <div class="section-title">
          <i class="fas fa-comments" />
          最新评论
        </div>
        <div
          v-for="comment in latestComments"
          :key="comment.id"
          class="activity-item comment"
          @click="goToArticle(comment.articleId)"
        >
          <div class="activity-avatar">
            <img :src="comment.avatar" :alt="comment.username" />
          </div>
          <div class="activity-content">
            <div class="activity-user">
              <span class="username">{{ comment.username }}</span>
              <span class="action">评论了</span>
            </div>
            <div class="activity-preview">{{ comment.content }}</div>
            <div class="activity-meta">
              <span class="article-title">{{ comment.articleTitle }}</span>
              <span class="time">{{ formatTime(comment.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 最新文章 -->
      <div v-if="latestArticles.length > 0" class="activity-section">
        <div class="section-title">
          <i class="fas fa-file-alt" />
          最新发布
        </div>
        <div
          v-for="article in latestArticles"
          :key="article.id"
          class="activity-item article"
          @click="goToArticle(article.id)"
        >
          <div class="activity-icon">
            <i class="fas fa-pencil-alt" />
          </div>
          <div class="activity-content">
            <div class="activity-user">
              <span class="username">{{ article.author }}</span>
              <span class="action">发布了文章</span>
            </div>
            <div class="activity-preview">{{ article.title }}</div>
            <div class="activity-meta">
              <span class="category">{{ article.category }}</span>
              <span class="time">{{ formatTime(article.publishTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户动态 -->
      <div v-if="userActivities.length > 0" class="activity-section">
        <div class="section-title">
          <i class="fas fa-users" />
          用户动态
        </div>
        <div
          v-for="activity in userActivities"
          :key="activity.id"
          class="activity-item user"
          @click="handleUserActivity(activity)"
        >
          <div class="activity-icon">
            <i :class="getActivityIcon(activity.type)" />
          </div>
          <div class="activity-content">
            <div class="activity-user">
              <span class="username">{{ activity.username }}</span>
              <span class="action">{{ getActivityText(activity.type) }}</span>
            </div>
            <div v-if="activity.target" class="activity-preview">{{ activity.target }}</div>
            <div class="activity-meta">
              <span class="time">{{ formatTime(activity.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 系统公告 -->
      <div v-if="systemNotices.length > 0" class="activity-section">
        <div class="section-title">
          <i class="fas fa-bullhorn" />
          系统公告
        </div>
        <div
          v-for="notice in systemNotices"
          :key="notice.id"
          class="activity-item notice"
          @click="showNoticeDetail(notice)"
        >
          <div class="activity-icon notice">
            <i class="fas fa-info-circle" />
          </div>
          <div class="activity-content">
            <div class="activity-user">
              <span class="action system">{{ notice.title }}</span>
            </div>
            <div class="activity-preview">{{ notice.content }}</div>
            <div class="activity-meta">
              <span class="time">{{ formatTime(notice.createTime) }}</span>
              <span v-if="notice.important" class="important">重要</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 查看更多 -->
    <div class="view-more" @click="viewMoreActivities">
      查看更多动态
      <i class="fas fa-arrow-right" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { onMounted, onUnmounted, ref } from 'vue';

const router = useRouter();

const isRefreshing = ref(false);
const lastUpdateTime = ref('刚刚');

// 最新评论数据
const latestComments = ref([
  {
    id: 1,
    username: '张三',
    avatar: '/static/img/avatar1.jpg',
    content: '这篇文章写得很详细，学到了很多！',
    articleTitle: 'Vue 3 Composition API 最佳实践',
    articleId: 1,
    createTime: new Date(Date.now() - 5 * 60 * 1000)
  },
  {
    id: 2,
    username: '李四',
    avatar: '/static/img/avatar2.jpg',
    content: '请问这个方案在实际项目中应用效果如何？',
    articleTitle: '前端性能优化实战指南',
    articleId: 2,
    createTime: new Date(Date.now() - 15 * 60 * 1000)
  }
]);

// 最新文章数据
const latestArticles = ref([
  {
    id: 3,
    author: '王五',
    title: '深入理解 JavaScript 闭包机制',
    category: 'JavaScript',
    publishTime: new Date(Date.now() - 30 * 60 * 1000)
  },
  {
    id: 4,
    author: '赵六',
    title: 'TypeScript 类型体操进阶技巧',
    category: 'TypeScript',
    publishTime: new Date(Date.now() - 45 * 60 * 1000)
  }
]);

// 用户动态数据
const userActivities = ref([
  {
    id: 1,
    username: '小明',
    type: 'like',
    target: '《React Hooks 完全指南》',
    createTime: new Date(Date.now() - 20 * 60 * 1000)
  },
  {
    id: 2,
    username: '小红',
    type: 'follow',
    target: '关注了作者 张三',
    createTime: new Date(Date.now() - 40 * 60 * 1000)
  }
]);

// 系统公告数据
const systemNotices = ref([
  {
    id: 1,
    title: '系统维护通知',
    content: '今晚22:00-24:00进行系统维护，期间可能无法访问',
    createTime: new Date(Date.now() - 60 * 60 * 1000),
    important: true
  }
]);

let refreshTimer: NodeJS.Timeout | null = null;

// 获取动态图标
const getActivityIcon = (type: string) => {
  const icons = {
    like: 'fas fa-heart',
    follow: 'fas fa-user-plus',
    collect: 'fas fa-bookmark',
    share: 'fas fa-share'
  };
  return icons[type] || 'fas fa-circle';
};

// 获取动态文本
const getActivityText = (type: string) => {
  const texts = {
    like: '点赞了',
    follow: '关注了',
    collect: '收藏了',
    share: '分享了'
  };
  return texts[type] || '操作了';
};

// 格式化时间
const formatTime = (time: Date) => {
  const now = new Date();
  const diff = now.getTime() - time.getTime();
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  return time.toLocaleDateString();
};

// 跳转到文章详情
const goToArticle = (id: number) => {
  router.push({
    name: 'blogViewShow',
    params: { blogId: String(id) }
  });
};

// 处理用户动态
const handleUserActivity = (activity: any) => {
  // 根据动态类型执行不同操作
  if (activity.type === 'like') {
    // 跳转到点赞的文章
    goToArticle(activity.targetId);
  } else if (activity.type === 'follow') {
    // 跳转到用户主页
    router.push({ name: 'userProfile', params: { userId: activity.targetUserId } });
  }
};

// 显示公告详情
const showNoticeDetail = (notice: any) => {
  ElMessage.info(notice.content);
};

// 查看更多动态
const viewMoreActivities = () => {
  router.push({ name: 'activityList' });
};

// 自动刷新
const refreshActivities = async () => {
  isRefreshing.value = true;
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 1000));
  lastUpdateTime.value = '刚刚';
  isRefreshing.value = false;
};

// 更新最后更新时间
const updateLastUpdateTime = () => {
  const times = ['刚刚', '1分钟前', '2分钟前', '3分钟前', '5分钟前'];
  let index = 0;

  const update = () => {
    if (index < times.length - 1) {
      index++;
      lastUpdateTime.value = times[index];
    }
  };

  refreshTimer = setInterval(update, 60000); // 每分钟更新一次
};

onMounted(() => {
  updateLastUpdateTime();
  // 每5分钟自动刷新一次数据
  setInterval(refreshActivities, 5 * 60 * 1000);
});

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
});
</script>

<style scoped lang="scss">
.panel {
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 16px;
}

.panel-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 16px;
  font-size: 1rem;
  position: relative;

  i {
    color: #10b981;
    font-size: 1.1rem;
  }

  .auto-refresh {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 0.75rem;
    color: #94a3b8;

    .refresh-icon {
      font-size: 0.8rem;

      &.rotating {
        animation: rotate 1s linear infinite;
      }
    }

    .refresh-text {
      font-weight: 400;
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 600px;
  overflow-y: auto;
  padding-right: 4px;

  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 2px;
  }

  &::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 2px;

    &:hover {
      background: #94a3b8;
    }
  }
}

.activity-section {
  .section-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.9rem;
    font-weight: 600;
    color: #475569;
    margin-bottom: 10px;
    position: sticky;
    top: -16px;
    background: white;
    padding: 8px 0;
    z-index: 1;

    i {
      font-size: 0.8rem;
      color: #10b981;
    }
  }
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;

  &:hover {
    background: #f8fafc;
    border-left-color: #10b981;
    transform: translateX(2px);
  }

  &.comment {
    border-left-color: #3b82f6;
  }

  &.article {
    border-left-color: #f59e0b;
  }

  &.user {
    border-left-color: #8b5cf6;
  }

  &.notice {
    border-left-color: #ef4444;
  }

  .activity-avatar {
    flex-shrink: 0;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .activity-icon {
    flex-shrink: 0;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: #f1f5f9;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #64748b;
    font-size: 0.8rem;

    &.notice {
      background: #fee2e2;
      color: #ef4444;
    }
  }

  .activity-content {
    flex: 1;
    min-width: 0;

    .activity-user {
      display: flex;
      align-items: center;
      gap: 6px;
      margin-bottom: 4px;
      font-size: 0.85rem;

      .username {
        font-weight: 600;
        color: #1e293b;
      }

      .action {
        color: #64748b;

        &.system {
          font-weight: 600;
          color: #1e293b;
        }
      }
    }

    .activity-preview {
      font-size: 0.8rem;
      color: #475569;
      line-height: 1.4;
      margin-bottom: 6px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .activity-meta {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 0.75rem;
      color: #94a3b8;

      .article-title {
        color: #64748b;
        max-width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .category {
        background: #f1f5f9;
        color: #3b82f6;
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 0.7rem;
      }

      .important {
        background: #fee2e2;
        color: #ef4444;
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 0.7rem;
        font-weight: 600;
      }
    }
  }
}

.view-more {
  margin-top: 16px;
  padding: 10px;
  background: #f8fafc;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 0.85rem;
  color: #3b82f6;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: #e2e8f0;
    transform: translateY(-1px);

    i {
      transform: translateX(2px);
    }
  }

  i {
    transition: transform 0.2s ease;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.activity-item {
  animation: fadeInUp 0.3s ease-out;
}
</style>